package com.chatai.filter;

import com.chatai.config.JwtUtils;
import com.chatai.service.AuthService;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.NonNull;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class);
    
    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private AuthService authService;
    
    // 不需要认证的路径列表
    private static final List<String> PUBLIC_PATHS = Arrays.asList(
        "/api/auth/register",
        "/api/auth/login",
        "/api/auth/logout", // 退出登录接口也不需要认证
        "/swagger-ui/**",
        "/v3/api-docs/**",
        "/api/file/download/**",
        "/api/test/health", // 添加测试端点
        "/api/test/echo",    // 添加测试端点
        "/api/ai/models",    // 添加AI模型端点
        "/api/ai/chat",       // 添加AI聊天端点
        "/api/chat/rooms",    // 添加聊天室列表端点
        "/api/chat/rooms/**"  // 添加所有聊天室相关端点
    );

    @Override
    protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain chain)
            throws ServletException, IOException {
        try {
            // 对于公开路径，直接放行，不进行JWT验证
            String requestUri = request.getRequestURI();
            logger.info("处理请求: {}", requestUri);
            
            for (String publicPath : PUBLIC_PATHS) {
                if (requestUri.equals(publicPath) || (publicPath.endsWith("/**") && requestUri.startsWith(publicPath.substring(0, publicPath.length() - 3)))) {
                    logger.info("公开路径，直接放行: {}", requestUri);
                    chain.doFilter(request, response);
                    return;
                }
            }

            final String requestTokenHeader = request.getHeader("Authorization");

            // 如果没有Authorization头，让请求继续通过过滤器链，由后续的SecurityConfig决定是否允许访问
            if (requestTokenHeader == null || !requestTokenHeader.startsWith("Bearer ")) {
                logger.info("没有有效的Authorization头，让请求继续通过过滤器链: {}", requestUri);
                chain.doFilter(request, response);
                return;
            }

            String jwtToken = requestTokenHeader.substring(7);
            String username = null;
            
            try {
                username = jwtUtils.extractUsername(jwtToken);
                logger.info("从JWT Token中提取到用户名: {}", username);
            } catch (Exception e) {
                logger.error("无法从JWT Token中提取用户名: {}", e.getMessage(), e);
                // 不要抛出异常，让请求继续通过过滤器链
                chain.doFilter(request, response);
                return;
            }

            // 验证token
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                try {
                    UserDetails userDetails = this.authService.loadUserByUsername(username);
                    
                    // 验证令牌是否有效
                    if (jwtUtils.validateToken(jwtToken, username)) {
                        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                                userDetails, null, userDetails.getAuthorities());
                        usernamePasswordAuthenticationToken
                                .setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                        // 设置认证信息到上下文中
                        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
                        logger.info("JWT认证成功，用户: {}", username);
                    } else {
                        logger.warn("JWT Token无效: {}", jwtToken);
                    }
                } catch (Exception e) {
                    logger.error("JWT认证过程中发生错误: {}", e.getMessage(), e);
                    // 不要抛出异常，让请求继续通过过滤器链
                }
            }
        } catch (Exception e) {
            logger.error("JWT过滤器处理请求时发生错误: {}", e.getMessage(), e);
            // 捕获所有异常，确保请求继续通过过滤器链
        }
        
        // 确保请求总是继续通过过滤器链
        chain.doFilter(request, response);
    }
}